package com.example.huajia.wx.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.BooleanUtil;
import com.example.huajia.wx.common.util.R;
import com.example.huajia.wx.config.shiro.JwtUtil;
import com.example.huajia.wx.db.pojo.CommentEntity;
import com.example.huajia.wx.db.pojo.DynamicEntity;
import com.example.huajia.wx.exception.HJException;
import com.example.huajia.wx.service.UserService;
import com.example.huajia.wx.service.impl.CommentServiceImpl;
import com.example.huajia.wx.service.impl.DynamicServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.example.huajia.wx.common.util.RedisKey.*;

@RestController
@RequestMapping("/dynamic")
@Api("动态模块接口")
public class DynamicController {

    @Resource
    DynamicServiceImpl dynamicService;

    @Resource
    CommentServiceImpl commentService;

    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

    /**
     * 发布动态
     *
     * @param entity 动态实体
     * @param token  token
     * @return (dynamicId - > 该动态的id)
     */
    @PostMapping("/insertDynamic")
    @ApiOperation("发布动态")
    public R insertDynamic(@RequestBody DynamicEntity entity, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        //先去redis查询是否存在
        String key = USER_INFO_KEY + userId;
        List<HashMap> range = redisTemplate.opsForList().range(key, 0, 40);
        String promulgatorName;
        String promulgatorImage;
        if (range.isEmpty()) {
            //如果为空，则需调用数据库查询
            ArrayList<HashMap> list = userService.searchUserById(userId);
            promulgatorName = (String) list.get(0).get("nickname");
            promulgatorImage = (String) list.get(0).get("photo");
            entity.setPromulgatorName(promulgatorName);
            entity.setPromulgatorImage(promulgatorImage);
            entity.setPromulgator(String.valueOf(userId));
            entity.setLike(new ArrayList());
            String dynamicId = dynamicService.insertDynamic(entity);
            if (dynamicId == null)
                return R.error();
            return R.ok().put("dynamicId", dynamicId);
        }
        promulgatorName = (String) range.get(0).get("nickname");
        promulgatorImage = (String) range.get(0).get("photo");
        entity.setPromulgatorName(promulgatorName);
        entity.setPromulgatorImage(promulgatorImage);
        entity.setPromulgator(String.valueOf(userId));
        entity.setLike(new ArrayList());
        String dynamicId = dynamicService.insertDynamic(entity);
        if (dynamicId == null)
            return R.error();
        return R.ok().put("dynamicId", dynamicId);
    }

    /**
     * 关键字搜索内容（动态内容）
     *
     * @param content 搜索关键字
     * @return (result - > 动态列表)
     */
    @GetMapping("/searchDynamic")
    @ApiOperation("关键字搜索内容（动态内容）")
    public R searchDynamic(@Param("content") String content) {
        List<DynamicEntity> list = dynamicService.searchDynamic(content);
        if (list == null)
            return R.error();
        return R.ok().put("result", list);
    }

    /**
     * 查找同城动态
     *
     * @param city 当前用户城市
     * @return (result - > 动态列表)
     */
    @GetMapping("/searchCityWide")
    @ApiOperation("查找同城动态")
    public R searchCityWide(@Param("city") String city) {
        if (city == null) {
            throw new HJException("城市不能为空！");
        }
        //先判断redis里面是否存在数据
        String key = DYNAMIC_ALL_KEY + city + ":";
        List<DynamicEntity> range = redisTemplate.opsForList().range(key, 0, 88);
        if (range.isEmpty()) {
            List<DynamicEntity> list = dynamicService.searchCityWide(city);
            if (list == null)
                return R.error();
            return R.ok().put("result", list);
        }
        return R.ok().put("result", range);
    }

    /**
     * 查看我的动态
     *
     * @param token token
     * @return (result - > 我的动态列表)
     */
    @GetMapping("/searchMyDynamic")
    @ApiOperation("查看我的动态")
    public R searchMyDynamic(@RequestHeader("token") String token) {
        Integer userId = jwtUtil.getUserId(token);
        //先到redis查询有没有数据
        String key = DYNAMIC_MINE_KEY + userId + ":";
        List<DynamicEntity> range = redisTemplate.opsForList().range(key, 0, 88);
        if (range.isEmpty()) {
            List<DynamicEntity> list = dynamicService.searchMyDynamic(userId.toString());
            return R.ok().put("result", list);
        }
        return R.ok().put("result", range);
    }

    /**
     * 查看我的动态
     *
     * @param token token
     * @return (result - > 我的动态列表)
     */
    @GetMapping("/searchHotDynamic")
    @ApiOperation("查询推荐动态")
    public R searchHotDynamic(@RequestHeader("token") String token) {
        Integer userId = jwtUtil.getUserId(token);
        //先到redis查询有没有数据
        String key = DYNAMIC_HOT_KEY;
        List<DynamicEntity> range = redisTemplate.opsForList().range(key, 0, 88);
        if (range.isEmpty()) {
            List<DynamicEntity> list = dynamicService.searchHotDynamic();
            return R.ok().put("result", list);
        }
        return R.ok().put("result", range);
    }

    /**
     * 查看动态详情
     *
     * @param dynamicId 动态id
     * @return (result - > 动态详情)
     */
    @GetMapping("/detail")
    @ApiOperation("查看动态详情")
    public R detail(@Param("dynamicId") String dynamicId) {
        DynamicEntity dynamic = dynamicService.detail(dynamicId);
        if (dynamic == null)
            return R.error();
        return R.ok().put("result", dynamic);
    }

    /**
     * 逻辑删除动态
     *
     * @param dynamicId 动态id
     * @return 是否删除成功
     */
    @PostMapping("/delete")
    @ApiOperation("逻辑删除动态")
    public R deleteDynamicById(@Param("dynamicId") String dynamicId) {
        long l = dynamicService.deleteDynamicById(dynamicId);
        if (l == 0)
            return R.error("删除失败");
        return R.ok("删除成功");
    }

    /**
     * 在动态下发布直接评论
     *
     * @param dynamicId 动态id
     * @param comment   要添加的评论
     * @return (result - > 新添加的动态id)
     */
    @PostMapping("/addComment/{dynamicId}")
    @ApiOperation("在动态下发布直接评论")
    public R addComment(@PathVariable String dynamicId, @RequestBody CommentEntity comment, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        comment.setPromulgator(String.valueOf(userId));
        String commentId = dynamicService.insertComment(dynamicId, comment);
        String key = DYNAMICS_COMMENTS_KEY + dynamicId + ":";
        String key1 = DYNAMIC_HOT_KEY;
        String key2 = DYNAMICS_HOT_COMMENTS_KEY + dynamicId + ":";
        redisTemplate.expire(key, 0, TimeUnit.SECONDS);
        redisTemplate.expire(key1, 0, TimeUnit.SECONDS);
        redisTemplate.expire(key2, 0, TimeUnit.SECONDS);
        return R.ok().put("result", commentId);
    }

    /**
     * 删除直接下级评论
     *
     * @param dynamicId 动态id
     * @param commentId 一级评论id
     * @return 是否删除成功
     */
    @GetMapping("/removeComment/")
    @ApiOperation("删除直接下级评论")
    public R deleteComment(@Param("dynamicId") String dynamicId, @Param("commentId") String commentId) {
        long l = dynamicService.deleteComment(dynamicId, commentId);
        if (l == 0L)
            return R.error("删除失败");
        return R.ok("删除成功");
    }

    /**
     * 点赞
     *
     * @param dynamicId 动态id
     * @param token     token
     * @return 是否点赞成功
     */
    @GetMapping("/insertLike")
    @ApiOperation("点赞")
    public R insertLike(@Param("dynamicId") String dynamicId, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        long l = dynamicService.insertLike(dynamicId, String.valueOf(userId));
        if (l == 0L)
            return R.error();
        return R.ok();
    }

    /**
     * 点赞评论
     *
     * @param dynamicId 动态id
     * @param token     token
     * @return 是否点赞成功
     */
    @GetMapping("/inserCommentLike")
    @ApiOperation("点赞评论")
    public R insertCommentLike(@Param("dynamicId") String dynamicId, @RequestHeader("token") String token, @Param("commentId") String commentId) {
        int userId = jwtUtil.getUserId(token);
        long l = dynamicService.insertCommentLike(dynamicId, String.valueOf(userId), commentId);
        if (l == 0L)
            return R.error();
        return R.ok();
    }

    /**
     * 取消点赞
     *
     * @param dynamicId 动态id
     * @param token     token
     * @return 是否删除成功
     */
    @GetMapping("/deleteLike")
    @ApiOperation("取消点赞")
    public R deleteLike(@Param("dynamicId") String dynamicId, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        long l = dynamicService.deleteLike(dynamicId, String.valueOf(userId));
        if (l == 0L)
            return R.error();
        return R.ok();
    }

    /**
     * 取消点赞评论
     *
     * @param dynamicId 动态id
     * @param token     token
     * @return 是否删除成功
     */
    @GetMapping("/deleteCommentLike")
    @ApiOperation("取消点赞评论")
    public R deleteCommentLike(@Param("dynamicId") String dynamicId, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        long l = dynamicService.deleteLike(dynamicId, String.valueOf(userId));
        if (l == 0L)
            return R.error();
        return R.ok();
    }

    /**
     * 获取dynamic下的所有comment
     *
     * @param dynamicId 动态id
     * @return (result - > 该动态下的所有评论)
     */
    @GetMapping("/getComments")
    @ApiOperation("获取dynamic下的所有comment")
    public R getComments(@Param("dynamicId") String dynamicId) {
        //先在redis查询数据是否存在
        String key = DYNAMICS_COMMENTS_KEY + dynamicId + ":";
        List<CommentEntity> range = redisTemplate.opsForList().range(key, 0, 10000);
        if (range.isEmpty()) {
            List<CommentEntity> list = dynamicService.getComments(dynamicId);
            if (list == null)
                return R.error();
            return R.ok().put("result", list);
        }
        return R.ok().put("result", range);
    }

    /**
     * 获取dynamic下的所有comment
     *
     * @param dynamicId 动态id
     * @return (result - > 该动态下的所有评论)
     */
    @GetMapping("/getHotComments")
    @ApiOperation("获取dynamic下的所有推荐的评论")
    public R getHotComments(@Param("dynamicId") String dynamicId) {
        //先在redis查询数据是否存在
        String key = DYNAMICS_HOT_COMMENTS_KEY + dynamicId + ":";
        List<CommentEntity> range = redisTemplate.opsForList().range(key, 0, 10000);
        if (range.isEmpty()) {
            List<CommentEntity> list = dynamicService.getHotComments(dynamicId);
            if (list == null)
                return R.error();
            return R.ok().put("result", list);
        }
        return R.ok().put("result", range);
    }


    /**
     * 添加评论下的评论
     *
     * @param superId 该评论回复的评论
     * @param comment 要添加的评论
     * @param token   token
     * @return (result - > 添加评论后 ， 该动态下的所有评论区)
     */
    @PostMapping("/insertComment/{superId}")
    @ApiOperation("添加评论下的评论")
    public R insertComment(@Param("dynamicId") String dynamicId, @PathVariable String superId, @RequestBody CommentEntity comment, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        System.out.println(superId);
        comment.setPromulgator(String.valueOf(userId));
        List<CommentEntity> list = commentService.insertComment(superId, comment);
        String key = DYNAMICS_COMMENTS_KEY + superId + ":";
        String key1 = DYNAMIC_HOT_KEY;
        String key2 = DYNAMICS_HOT_COMMENTS_KEY + superId + ":";
        redisTemplate.expire(key, 0, TimeUnit.SECONDS);
        redisTemplate.expire(key1, 0, TimeUnit.SECONDS);
        redisTemplate.expire(key2, 0, TimeUnit.SECONDS);
        if (list == null)
            return R.error();
        return R.ok().put("result", list);
    }

    /**
     * 删除评论下的评论
     *
     * @param id 要删除的评论id
     * @return (result - > 删除后 ， 该动态下的所有评论区)
     */
    @PostMapping("/deleteComment/{id}")
    @ApiOperation("删除评论下的评论")
    public R deleteComment(@PathVariable String id) {
        List<CommentEntity> list = commentService.deleteComment(id);
        if (list == null)
            return R.error();
        return R.ok().put("result", list);
    }

    @GetMapping("/giveThumbs")
    @ApiOperation("点赞接口")
    public R giveThumbs(@RequestHeader("token") String token, @Param("dynamicId") String dynamicId, @Param("city") String city) {
        // 1.获取登录用户
        int userId = jwtUtil.getUserId(token);
        // 2.判断当前登录用户是否已经点赞
        String key = "dynamics:thumbs:" + dynamicId + ":";
        Boolean isMember = redisTemplate.opsForSet().isMember(key, userId);
        if (BooleanUtil.isFalse(isMember)) {
            //3.如果未点赞，可以点赞
            //3.1 数据库点赞数+1
            long count = dynamicService.insertLike(dynamicId, String.valueOf(userId));
            //3.2 保存用户到Redis的set集合
            if (count != 0) {
                redisTemplate.opsForSet().add(key, userId);
            }
            String key1 = DYNAMIC_ALL_KEY + city + ":";
            String key2 = DYNAMIC_MINE_KEY + userId + ":";
            String key3 = DYNAMIC_HOT_KEY;
            redisTemplate.expire(key1, 0, TimeUnit.SECONDS);
            redisTemplate.expire(key2, 0, TimeUnit.SECONDS);
            redisTemplate.expire(key3, 0, TimeUnit.SECONDS);
            return R.ok().put("result", true);
        } else {
            //4.如果已点赞，取消点赞
            //4.1 数据库点赞数-1
            long count = dynamicService.deleteLike(dynamicId, String.valueOf(userId));
            //4.2 把用户从Redis的set集合移除
            if (count != 0) {
                redisTemplate.opsForSet().remove(key, userId);
            }
            String key1 = DYNAMIC_ALL_KEY + city + ":";
            String key2 = DYNAMIC_MINE_KEY + userId + ":";
            String key3 = DYNAMIC_HOT_KEY;
            redisTemplate.expire(key1, 0, TimeUnit.SECONDS);
            redisTemplate.expire(key2, 0, TimeUnit.SECONDS);
            redisTemplate.expire(key3, 0, TimeUnit.SECONDS);
            return R.ok().put("result", false);
        }
    }

    @GetMapping("/giveCommentThumbs")
    @ApiOperation("点赞接口")
    public R giveCommentThumbs(@RequestHeader("token") String token, @Param("dynamicId") String dynamicId, @Param("city") String city, @Param("commentId") String commentId) {
        // 1.获取登录用户
        int userId = jwtUtil.getUserId(token);
        // 2.判断当前登录用户是否已经点赞
        String key = "dynamics:commentThumbs:" + commentId + ":";
        Boolean isMember = redisTemplate.opsForSet().isMember(key, userId);
        if (BooleanUtil.isFalse(isMember)) {
            //3.如果未点赞，可以点赞
            //3.1 数据库点赞数+1
//            long count = dynamicService.insertLike(dynamicId, String.valueOf(userId));
            long count = dynamicService.insertCommentLike(dynamicId, String.valueOf(userId), commentId);
            //3.2 保存用户到Redis的set集合
            if (count != 0) {
                redisTemplate.opsForSet().add(key, userId);
            }
            String key1 = DYNAMICS_COMMENTS_KEY + dynamicId + ":";
            String key2 = DYNAMICS_HOT_COMMENTS_KEY + dynamicId + ":";
            redisTemplate.expire(key1, 0, TimeUnit.SECONDS);
            redisTemplate.expire(key2, 0, TimeUnit.SECONDS);
            return R.ok().put("result", true);
        } else {
            //4.如果已点赞，取消点赞
            //4.1 数据库点赞数-1
            long count = dynamicService.deleteCommentLike(dynamicId, String.valueOf(userId), commentId);
            //4.2 把用户从Redis的set集合移除
            if (count != 0) {
                redisTemplate.opsForSet().remove(key, userId);
            }
            String key1 = DYNAMICS_COMMENTS_KEY + dynamicId + ":";
            String key2 = DYNAMICS_HOT_COMMENTS_KEY + dynamicId + ":";
            redisTemplate.expire(key1, 0, TimeUnit.SECONDS);
            redisTemplate.expire(key2, 0, TimeUnit.SECONDS);
            return R.ok().put("result", false);
        }
    }
}
